package com.example.teachingSystem.interceptor;

import com.example.teachingSystem.utils.JwtHelper;
import com.example.teachingSystem.utils.result.Result;
import com.example.teachingSystem.utils.result.ResultCodeEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginProtectInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtHelper jwtHelper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("Authorization");
        if (StringUtils.isEmpty(token) || jwtHelper.isExpiration(token)){
            Result<Object> result = Result.build(null, ResultCodeEnum.NOTLOGIN);
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(result);
            response.setContentType("application/json"); // 设置响应的Content-Type为JSON
            response.setCharacterEncoding("UTF-8"); // 设置响应的字符编码为UTF-8
            response.getWriter().print(json); // 将JSON字符串写入响应的输出流
            //拦截
            return false;
        }else{
            //放行
            return true;
        }
    }
}
